package com.jhc.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhc.dto.*;
import com.jhc.entity.BacTerm;
import com.jhc.entity.BacWeekDate;
import com.jhc.mapper.BacTermMapper;
import com.jhc.mapper.BacWeekDateMapper;
import com.jhc.service.IBacTermService;
import com.jhc.service.IBacWeekDateService;
import com.jhc.utils.JHC;
import com.jhc.utils.VerifyPageDtoUtil;
import com.jhc.vo.PageVo;
import com.jhc.vo.DateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 学期信息  服务实现类
 * </p>
 *
 * @author zhuzhixu
 */
@Service
public class BacTermServiceImpl extends ServiceImpl<BacTermMapper, BacTerm> implements IBacTermService {
    @Autowired
    private BacWeekDateMapper bacWeekDateMapper;

    @Autowired
    private IBacWeekDateService bacWeekDateService;

    @Autowired
    private BacTermMapper bacTermMapper;

    @Override
    public IPage<BacTermViewDto> getTeacherPageData(PageVo<BacTermSearchDto> pageVo) {
        //防止传入filter数据为null
        if (ObjectUtil.isNull(pageVo.getFilter())) {
            pageVo.setFilter(new BacTermSearchDto());
        }

        //构造分页参数
        BacTermSearchDto searchDto = pageVo.getFilter();
        Page page = new Page(pageVo.getCurrentPage(), pageVo.getPageSize());
        //查询院系分页数据
        IPage<BacTermViewDto> viewDtoIPage = bacTermMapper.getTeacherPageData(page, searchDto);
        return viewDtoIPage;
    }

    /**
     * 添加学期信息
     *
     * @param bacTermAddDto
     * @return
     */
    @Override
    public Boolean addTerm(BacTermAddDto bacTermAddDto) {
        // 插入学期表
        BacTerm bacTerm = new BacTerm();
        BeanUtils.copyProperties(bacTermAddDto, bacTerm);
        System.out.println(JSON.toJSONString(bacTerm));
        Long termId = 0L;
        if (bacTermMapper.insert(bacTerm) != 1) {
            return false;
        }
        bacTerm = bacTermMapper.selectOne(new QueryWrapper<BacTerm>().lambda().
                select(BacTerm::getId).eq(BacTerm::getTermName, bacTerm.getTermName()));
        termId = bacTerm.getId();
        // 插入周次表
        List<BacWeekDate> bacWeekDateList = new ArrayList<>();
        // 一个学期多少周
        int allWeeks = bacTermAddDto.getTeachingWeek();
        Date calculateDate = bacTermAddDto.getOpeningDate();
        for (int i = 0; i < allWeeks; i++) {
            BacWeekDate bacWeekDate = new BacWeekDate();
            // 设置学期ID
            bacWeekDate.setTermId(termId);
            // 设置周次
            bacWeekDate.setWeek(i + 1);
            // 开始时间
            bacWeekDate.setStartDay(calculateDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(calculateDate);
            if (i == 0) {
                // 第一周
                int week = calendar.getFirstDayOfWeek();
                bacWeekDate.setEndDay(JHC.getDate(calculateDate, 6 - week));
                calculateDate = JHC.getDate(calculateDate, 7 - week);
            } else {
                bacWeekDate.setEndDay(JHC.getDate(calculateDate, 6));
                calculateDate = JHC.getDate(calculateDate, 7);
            }
            bacWeekDateList.add(bacWeekDate);
        }
        if (bacWeekDateService.saveBatch(bacWeekDateList)) {
            return true;
        }
        bacTermMapper.deleteById(termId);
        return false;
    }

    /**
     * 获取学期开始结束日期
     *
     * @param date
     * @return
     */
    @Override
    public DateVo getTermDate(Date date) {
        String dateStr = JHC.toDateString(date);
        BacTerm term = bacTermMapper.selectOne(new QueryWrapper<BacTerm>().lambda().ge(BacTerm::getEndDate,dateStr).le(BacTerm::getOpeningDate,dateStr));
        DateVo dateVo = new DateVo();
        dateVo.setStartDate(term.getOpeningDate());
        dateVo.setEndDate(term.getEndDate());
        return dateVo;
    }

    /**
     * 获取当前学期
     *
     * @param date
     * @return
     */
    @Override
    public BacTerm getTerm(Date date) {
        String dateStr = JHC.toDateString(date);
        BacTerm term = bacTermMapper.selectOne(new QueryWrapper<BacTerm>().lambda().ge(BacTerm::getEndDate,dateStr).le(BacTerm::getOpeningDate,dateStr));
        return term;
    }

    /**
     * 获取开始结束日期
     *
     * @param termId
     * @return
     */
    @Override
    public DateVo getTermDate(Long termId) {
        if (termId==null){
            return getTermDate(new Date());
        }
        BacTerm term = bacTermMapper.selectById(termId);
        DateVo dateVo = new DateVo();
        dateVo.setStartDate(term.getOpeningDate());
        dateVo.setEndDate(term.getEndDate());
        return dateVo;
    }

    /**
     * 获取本学期及之前学期列表
     *
     * @return
     */
    @Override
    public List<TermIdAndNameDto> getTermList() {
        String dateStr = JHC.toDateString(new Date());
        //查询之前的学期列表
        List<BacTerm> terms = bacTermMapper.selectList(new QueryWrapper<BacTerm>().lambda()
                .le(BacTerm::getOpeningDate,dateStr)
                .orderByDesc(BacTerm::getOpeningDate));
        List<TermIdAndNameDto> termList = new ArrayList<>();
        terms.stream().forEach(item -> {
            TermIdAndNameDto termIdAndNameDto = new TermIdAndNameDto();
            termIdAndNameDto.setTermId(item.getId());
            termIdAndNameDto.setTermName(item.getTermName());
            termList.add(termIdAndNameDto);
        });
        return termList;
    }

    /**
     * 获取所有学期列表
     *
     * @return
     */
    @Override
    public List<TermIdAndNameDto> getAllTermList() {
        List<BacTerm> terms = bacTermMapper.selectList(new QueryWrapper<BacTerm>().lambda()
                .orderByDesc(BacTerm::getOpeningDate));
        List<TermIdAndNameDto> termList = new ArrayList<>();
        terms.stream().forEach(item ->{
            TermIdAndNameDto termIdAndNameDto = new TermIdAndNameDto();
            termIdAndNameDto.setTermId(item.getId());
            termIdAndNameDto.setTermName(item.getTermName());
            termList.add(termIdAndNameDto);
        });
        return termList;
    }

    /**
     * 获取一学期本周之前列表
     *
     * @return
     */
    @Override
    public List<WeekIdAndNameDto> getWeekList(Long termId) {
        String dateStr = JHC.toDateString(new Date());
        //周次列表
        List<BacWeekDate> weekDates = bacWeekDateMapper.selectList(new QueryWrapper<BacWeekDate>().lambda()
                .eq(BacWeekDate::getTermId,termId)
                .le(BacWeekDate::getStartDay,dateStr));
        List<WeekIdAndNameDto> weekList = new ArrayList<>();
        weekDates.stream().forEach(item -> {
            WeekIdAndNameDto weekIdAndNameDto = new WeekIdAndNameDto();
            weekIdAndNameDto.setWeekId(item.getId());
            weekIdAndNameDto.setWeek(item.getWeek());
            weekList.add(weekIdAndNameDto);
        });
        return weekList;
    }

    /**
     * 获取一学期所有列表
     *
     * @return
     */
    @Override
    public List<WeekIdAndNameDto> getAllWeekList(Long termId) {
        //周次列表
        List<BacWeekDate> weekDates = bacWeekDateMapper.selectList(new QueryWrapper<BacWeekDate>().lambda()
                .eq(BacWeekDate::getTermId,termId));
        List<WeekIdAndNameDto> weekList = new ArrayList<>();
        weekDates.stream().forEach(item -> {
            WeekIdAndNameDto weekIdAndNameDto = new WeekIdAndNameDto();
            weekIdAndNameDto.setWeekId(item.getId());
            weekIdAndNameDto.setWeek(item.getWeek());
            weekList.add(weekIdAndNameDto);
        });
        return weekList;
    }

    /**
     * 获取当前日期与周次
     *
     * @return
     */
    @Override
    public Map<String, Object> getNowDateInfo() {
        Map<String,Object> resultMap = new HashMap<>();
        //获取一个日历
        Calendar calendar = Calendar.getInstance();
        //获取当前日期
        Date nowDate = JHC.removeTime(new Date());
        //获取星期
        calendar.setTime(nowDate);
        Integer weekDate = calendar.get(Calendar.DAY_OF_WEEK)-1;
        if (weekDate<0){
            weekDate = 0;
        }
        resultMap.put("nowDate",nowDate);
        resultMap.put("weekDay",weekDate);
        //查询周次
        String dateStr = JHC.toDateString(nowDate);
        List<BacWeekDate> bacWeekDate = bacWeekDateMapper.selectList(new QueryWrapper<BacWeekDate>().lambda()
                .le(BacWeekDate::getStartDay,dateStr).ge(BacWeekDate::getEndDay,dateStr));
        if (bacWeekDate.size()==0){
            resultMap.put("week","假期期间");
        }else {
            resultMap.put("week",bacWeekDate.get(0).getWeek());
        }
        return resultMap;
    }
}
